/*
 * @Description: 登录token认证中间件
 * @Author: Yong
 * @Date: 2021-10-02 13:27:12
 * @LastEditTime: 2021-10-02 13:52:05
 */

import { Provide } from "@midwayjs/decorator"
import {
    IWebMiddleware,
    IMidwayKoaContext,
    IMidwayKoaNext,
} from "@midwayjs/koa"
import { verify, resHandler } from "../utils"

@Provide()
export class LoginAuth implements IWebMiddleware {
    resolve() {
        return async (ctx: IMidwayKoaContext, next: IMidwayKoaNext) => {
            const { url, header } = ctx
            const white = ['/user/login', '/user/register']
            if (white.indexOf(url) <= -1) {
                // 不是white的接口 需要token认证
                const Token = header['authorization'].split(' ')[1]
                const res = verify.verifyToken(Token)
                if (res == 'err') {
                    ctx.body = resHandler.errorRes({ msg: 'token异常或失效', code: -1 })
                } else {
                    await next()
                }
            } else {
                await next()
            }
        }
    }
}
